/**
 * Created by liyun on 2015/10/28.
 */
var knex = require('../utils/knex');
var Promise = require('bluebird');
var debug = require('debug')('models:shop_goods');
var shop_goods = function(){
    if(typeof this.list !='function'){
        shop_goods.prototype.list = function(page,callback){
            /*knex.select().table('shop_goods').then(function(data){
                callback(data);
            }).catch(function(err){
                callback(err);
            });*/

            countGoods(function(count){
                knex.select('*').from('shop_goods').whereIn('status',[0,1,2])/*.leftJoin('shop_goods_term',function(){
                    this.on('shop_goods.id','=','shop_goods_term.gid');//����
                })*/.orderBy(page[0], page[1])//����
                    .limit(page[3]).offset(page[2])//��ҳ
                    .then(function(data){
                        callback({total:count[0].count,rows:data});
                    }).catch(function(err){
                        callback(err);
                    });
            });

        }

    }

    if(typeof this.add !='function') {
        shop_goods.prototype.add = function (goods, callback) {
            goods.goodssn = "QM"+new Date().getTime();
            goods.createtime = new Date();
            /*knex('shop_goods').insert(goods).then(function(data){
                callback({msg:true});
            }).catch(function(err){
                callback({msg:false});
            });
*/


            knex.transaction(function(trx) {

                var lottery_nums = new Array();
                var nums = goods.productprice;
                for(var i=0;i<nums;i++){
                    lottery_nums[i] = {
                        lottery_num:10000000+i+1
                    };
                }
                lottery_nums.sort(function(){ return 0.5 - Math.random(); });
                goods.productprice = goods.productprice*100;
                return trx
                    .insert(goods, 'id')
                    .into('shop_goods')
                    .then(function(ids) {
                        for(var i=0;i<nums;i++){
                            lottery_nums[i].gid = ids[0];
                        }
                        return trx.insert(lottery_nums).into('lottery_num');
                        /*return Promise.map(lottery_nums, function(lottery_num) {


                            // Some validation could take place here.

                            return trx.insert(lottery_num).into('lottery_num');

                        });*/
                    });

            })
                .then(function(inserts) {
                    //console.log(inserts.length + ' new books saved.');
                    callback({msg:true});
                })
                .catch(function(error) {
                    callback({msg:false});
                });


            /* knex.transaction(function (trx) {

                 knex.insert(goods, 'id')
                     .into('shop_goods')
                     .transacting(trx)
                     .then(function (ids) {

                             // Some validation could take place here.
                         debug(ids);
                         var term = {
                             join:0,
                             state:'progress'
                         };
                             return knex.insert(info).into('shop_goods_term').transacting(trx);

                     })
                     .then(trx.commit)
                     .catch(trx.rollback);
             })
                 .then(function (inserts) {
                     console.log(inserts.length + ' new books saved.');
                 })
                 .catch(function (error) {
                     // If we get here, that means that neither the 'Old Books' catalogues insert,
                     // nor any of the books inserts will have taken place.
                     console.error(error);
                 });*/

        }
    }

    if(typeof this.edit !='function') {
        shop_goods.prototype.edit = function (goods, callback) {
            delete goods.oldthumb;
            knex('shop_goods')
                .where('id', '=', goods.id)
                .update(goods).then(function(data){
                callback({msg:true});
            }).catch(function(err){
                callback({msg:false});
            });

        }
    }
    if(typeof this.del !='function') {
        shop_goods.prototype.del = function (id, callback) {
            knex('shop_goods')
                .where('id', '=', id)
                .update({status:3}).then(function(data){
                callback({msg:true});
            }).catch(function(err){
                callback({msg:false});
            });

        }
    }
    if(typeof this.findOne !='function') {
        shop_goods.prototype.findOne = function (id, callback) {
            knex('shop_goods').where('id', '=', id)
                .then(function(data){
                callback(data);
            }).catch(function(err){
                callback(err);
            });

        }
    }

}

function countGoods(callback){
    knex('shop_goods').whereIn('status',[0,1,2]).count('id as count')
        .then(function(data){
        callback(data);
    }).catch(function(err){
        callback(err);
    });
}
module.exports.shop_goods = shop_goods;